package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.entity.*;
import com.project.mapper.IChargeRecordMapper;
import com.project.mapper.IPercentMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserRechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 预存款
 */
@Service
@Transactional
public class UserRechargeServiceImpl implements IUserRechargeService {

    @Autowired
    private IUserMapper mapper;

    @Autowired
    private IPercentMapper recordMapper;

    @Autowired
    private IChargeRecordMapper chargeRecordMapper;


    @Override
    public void buy(UserOrderEntity userOrderEntity) {
        //预存款购买商品
        QueryWrapper<UserEntity> qw = new QueryWrapper<>();
        qw.eq("u_num", userOrderEntity.getUserRef());
        UserEntity user = mapper.selectOne(qw);
        //判断预存款是否足够
        if (user.getBalance()-userOrderEntity.getTotalPrice()>=0) {
            user.setBalance(user.getBalance() - userOrderEntity.getTotalPrice());
            mapper.updateById(user);
        }
        else {
           String str= "你的余额不足";
        }
    }

    @Override
    public IPage<ChargeRecordEntity> findByItem(int pageNO, int pageSize) {
        // 创建一个 Page 对象，用于分页查询
        Page<ChargeRecordEntity> page = new Page<>(pageNO, pageSize);
        // 执行自定义 SQL 查询，将查询结果存储到一个 List 中
        List<ChargeRecordEntity> result = chargeRecordMapper.findUserTotalChargeRecord();
        // 将查询结果存储到 IPage 中
        IPage<ChargeRecordEntity> pageResult = new Page<>();
        pageResult.setRecords(result);
        pageResult.setTotal(page.getTotal());
        pageResult.setSize(page.getSize());
        pageResult.setCurrent(page.getCurrent());

        return pageResult;

    }




    @Override
    public ChargeRecordEntity findById(Integer id) {
        return chargeRecordMapper.selectById(id);
    }
}
